<?php

namespace App\Listeners;

use App\Events\ModelView;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Session\Store;

class ModelViewListener
{
    protected $session;

    /**
     * @var string
     */
    protected $sessionKey;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(Store $session)
    {
        $this->session = $session;
    }

    /**
     * Handle the event.
     *
     * @param  ModelView  $event
     * @return void
     */
    public function handle(ModelView $event)
    {
        $model = $event->model;
        $expireIn =$event->expireIn;
        $sessionKey = 'event_viewed_' . $event->tag . $model->id;

        if (!$this->hasViewedModel($sessionKey, $expireIn)) {
            $model->view_count += 1;
            $model->timestamps = false;
            $model->view_at = now();
            $model->save();

            // 看过文章后保存到session
            $this->storeViewedModel($sessionKey);
        }
    }

    protected function hasViewedModel($sessionKey, $expireIn)
    {
        $value = $this->session->get($sessionKey, 0);

        if ((time() - $value) > $expireIn) {
            return false;
        } else {
            return true;
        }
    }

    protected function storeViewedModel($sessionKey)
    {
        $this->session->put($sessionKey, time());
        return true;
    }
}
